package com.ihrm.company.service;

import cn.hutool.core.bean.BeanUtil;
import com.ihrm.common.entity.Result;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.company.dao.CompanyRepository;
import com.ihrm.domain.company.Company;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.Date;
import java.util.Optional;

@Service
public class CompanyService {

    @Autowired
    private CompanyRepository companyRepository;
    @Autowired
    private IdWorker idWorker;

    public Result<Void> addCompany(Company company){
        company.setId(String.valueOf(idWorker.nextId()));
        company.setCreateTime(new Date());
        company.setState(1); // 启用
        company.setAuditState("0"); // 待审核
        company.setBalance(0d);
        this.companyRepository.save(company);
        return Result.SUCCESS();
    }

    public Result<Void> updateCompany(String id, Company newCompany){
        Result<Company> result = this.findById(id);
        Company oldCompany = null;
        if(result.getCode() == 10000){
            oldCompany = result.getData();
            BeanUtil.copyProperties(newCompany, oldCompany);
        }
        oldCompany.setId(id);
        oldCompany.setCreateTime(new Date());
        this.companyRepository.save(oldCompany);
        return Result.SUCCESS();
    }

    public Result<Company> findById(String id){
        Optional<Company> optional = this.companyRepository.findById(id);
        if(optional.isPresent()){
            return Result.SUCCESS(optional.get());
        }
        return Result.FAIL();
    }

    public Result<Void> deleteById(String id){
        this.companyRepository.deleteById(id);
        return Result.SUCCESS();
    }

    public Result<Page<Company>> findAll(int pageNumber, int rows, String key, String field, Boolean sortStatus){
        Sort sort;
        if(!StringUtils.isEmpty(field)){
            sort = sortStatus ? Sort.by(Sort.Order.asc(field)) : Sort.by(Sort.Order.desc(field));
        }else{
            sort = Sort.unsorted();
        }
        // 构建分页条件
        Pageable pageable = PageRequest.of(pageNumber, rows, sort);
        Page<Company> page;
        if(!StringUtils.isEmpty(key)){
            // 由于条件可能比较复杂，所以建议使用JPA的自定义查询
            Specification<Company> specification = (root, criteriaQuery, criteriaBuilder) -> {
                // root 表示查询对象的根，基本上表示从哪个类里面查询数据
                // query是一个动态条件对象
                // criteriaBuilder用于构建动态条件
                // 最后把条件构建好以后，返回Predicate对象（谓词）
                Predicate namePredicate = criteriaBuilder.like(root.get("name"), "%" + key + "%");
                Predicate companyAreaPredicate = criteriaBuilder.like(root.get("companyArea"), "%" + key + "%");
                Predicate companyAddressPredicate = criteriaBuilder.like(root.get("companyAddress"), "%" + key + "%");
                Predicate companyPhonePredicate = criteriaBuilder.like(root.get("companyPhone"), "%" + key + "%");
                Predicate mailboxPredicate = criteriaBuilder.like(root.get("mailbox"), "%" + key + "%");
                Predicate legalRepresentativePredicate = criteriaBuilder.like(root.get("legalRepresentative"), "%" + key + "%");
                // 构建or查询
                // where name like ? or companyArea like ? ...
                return criteriaBuilder.or(namePredicate, companyAreaPredicate, companyAddressPredicate,
                        companyPhonePredicate, mailboxPredicate, legalRepresentativePredicate);
            };
            page = this.companyRepository.findAll(specification, pageable);
        }else {
            page = this.companyRepository.findAll(pageable);
        }
        return Result.SUCCESS(page);
    }
}
